//
//  AddAccountingView.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 23.03.25.
//

import SwiftUI

struct AddAccountingView: View {
    
    @Environment(\.presentToast) var presentToast
    @Environment(\.presentationMode) var presentationMode
    @StateObject var viewModel = AddAccountingViewModel()
    @State var categoryType: CategoryType = .expense
    @State private var isContinuousRecord = false
    @State var showBookChangeSheet = false
    @State var showCalendarSheet = false
    @State var navigationToBookManager = false
    @State var dateText = Date().toFriendlyString()
    @State var amountText = "0.00"
    @State var selectedDetail: AccountingDetailCombine? = nil
    
    @State private var keyboardHeight: CGFloat = 0
    @State private var activeTextFieldY: CGFloat = 0
    
    private var columns = [
        GridItem(.flexible(), alignment: .top),
        GridItem(.flexible(), alignment: .top),
        GridItem(.flexible(), alignment: .top),
        GridItem(.flexible(), alignment: .top),
        GridItem(.flexible(), alignment: .top)
    ]
    
    init(selectedDetail: AccountingDetailCombine? = nil) {
        _selectedDetail = State(wrappedValue: selectedDetail)
    }
    
    var body: some View {
        NavigationStack {
            VStack (spacing: 0){
                CategoryTypeView(categoryType: $categoryType)
                    .padding(EdgeInsets(top: 16, leading: 0, bottom: 6, trailing: 0))
                TabView(selection: $categoryType) {
                    CategoryGridView(
                        categoryList: $viewModel.expenseList,
                        subCategoryList: $viewModel.subCategoryList,
                        selectedCategory: $viewModel.selectedCategory,
                        selectedSubCategory: $viewModel.selectedSubCategory,
                        expand: $viewModel.isExpand,
                        onCategoryClick: { category in
                            viewModel.loadSubCategoryList(category: category)
                        }
                    ).tag(CategoryType.expense)
                    
                    CategoryGridView(
                        categoryList: $viewModel.incomeList,
                        subCategoryList: $viewModel.subCategoryList,
                        selectedCategory: $viewModel.selectedCategory,
                        selectedSubCategory: $viewModel.selectedSubCategory,
                        expand: $viewModel.isExpand,
                        onCategoryClick: { category in
                            viewModel.loadSubCategoryList(category: category)
                        }
                    ).tag(CategoryType.income)
                }
                .tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))
                .overlay(functionArea, alignment: .bottom)
                
                VStack {
                    HStack {
                        TextField("",text: $viewModel.remark, prompt: Text("点击添加备注").foregroundColor(Color.koiColorTitleSecond))
                            .font(.system(size: 15))
                            .foregroundColor(Color.koiColorTitle)
                            .fixedSize(horizontal: true, vertical: false)
                            .background(
                                GeometryReader { geometry in
                                    Color.clear
                                        .onAppear {
                                            activeTextFieldY = geometry.frame(in: .global).minY
                                        }
                                }
                            )
                        Spacer()
                        Button(action: {
                            hideKeyboard()
                        }) {
                            Text(viewModel.amount)
                                .font(.system(size: 28))
                                .foregroundColor(Color.koiColorPrimary)
                                .bold()
                                .fixedSize(horizontal: false, vertical: true)
                        }
                    }
                    .padding(EdgeInsets(top: 10, leading: 16, bottom: 10, trailing: 16))
                    .background(Color.white.cornerRadius(16))
                    .padding(.horizontal, 10)
                    NumericKeypadView(
                        numericClickCallback: { text in
                            viewModel.amount = text
                        },
                        doneClickCallback: {
                            viewModel.saveRecord()
                        },
                        reset: $viewModel.reset
                     )
                    .frame(height: 264)
                    .padding(EdgeInsets(top: 0, leading: 10, bottom: 0, trailing: 10))
                }.background(Color.koiColorBackgroundItem)
            }
            .onChange(of: viewModel.selectedDate) { newDate in
                dateText = newDate.toFriendlyString()
            }
            .sheet(isPresented: $showBookChangeSheet) {
                BookSelectSheetView(
                    selectedBookId: viewModel.selectedBook.bookId.orEmpty,
                    onSelectedBook: { selectedBook in
                        viewModel.selectedBook = selectedBook
                        // 切换账本，取消类比选中，除非是更新数据，有 selectedDetail
                        if selectedDetail?.book.bookId == selectedBook.bookId {
                            if let selectedDetail = selectedDetail {
                                // 从数据库中获取类别，包括一级类别，二级类别，和子类别集合
                                viewModel.loadCategorys(selectedCategory: selectedDetail.category)
                            }
                        } else {
                            viewModel.selectedCategory = nil
                            viewModel.selectedSubCategory = nil
                            viewModel.subCategoryList = Array()
                        }
                    
                        viewModel.loadCategorys()
                    },
                    onAddBook: {
                        // 新增账本，跳转到账本管理
                        navigationToBookManager = true
                    }
                )
            }
            .navigationDestination(isPresented: $navigationToBookManager, destination: {
                BookManagerView()
            })
            .koiSheet(isPresented: $showCalendarSheet) {
                CalendarView(selectedDate: $viewModel.selectedDate) { newDate in
                    viewModel.selectedDate = newDate
                }
            }
            .background(Color.koiColorBackground)
            .onChange(of: viewModel.toastMsg) { value in
                if value == "" { return }
                presentToast(.init(message: value))
                viewModel.toastMsg = ""
            }
            .onChange(of: viewModel.saveState) { value in
                if value == "success" {
                    viewModel.saveState = ""
                    if !isContinuousRecord {
                        KoiEvent.homeReload.send()
                        presentationMode.wrappedValue.dismiss()
                    } else {
                        viewModel.selectedCategory = nil
                        viewModel.selectedSubCategory = nil
                        viewModel.selectedDate = Date()
                        viewModel.subCategoryList = Array()
                        viewModel.amount = "0"
                        viewModel.remark = ""
                        viewModel.reset = true
                        presentToast(.init(message: "保存成功"))
                    }
                }
            }
            .onDisappear {
                NotificationCenter.default.removeObserver(self)
            }
            .offset(y: -keyboardHeight)
            .animation(.easeOut, value: keyboardHeight)
            .onAppear {
                listenToKeyboardNotifications()
                if let selectedDetail = selectedDetail {
                    // 账本
                    viewModel.selectedBook = selectedDetail.book
                    // 明细
                    viewModel.selectedDetail = selectedDetail.detail
                    // 类别类型
                    categoryType = viewModel.selectedCategory?.getCategoryType() ?? categoryType
                    // 日期
                    viewModel.selectedDate = selectedDetail.detail.date?.toDate() ?? Date()
                    dateText = selectedDetail.getDateText()
                    // 金额
                    viewModel.amount = selectedDetail.detail.amount?.toStringWithoutTrailingZeros() ?? "0"
                    // 备注
                    viewModel.remark = selectedDetail.detail.remark ?? ""
                    // 详情id
                    viewModel.recordId = selectedDetail.detail.recordId ?? ""
                    // 从数据库中获取明细数据
                    viewModel.initDetail()
                    // 从数据库中获取类别，包括一级类别，二级类别，和子类别集合
                    viewModel.loadCategorys(selectedCategory: selectedDetail.category)
                } else {
                    viewModel.loadCategorys()
                }
            }
            .ignoresSafeArea(.keyboard, edges: .bottom)
        }
        .presentationBackground(Color.koiColorBackground)
    }
    
    func listenToKeyboardNotifications() {
            NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: .main) { notification in
                if let keyboardFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect {
                    let keyboardTop = keyboardFrame.minY
                    let screenHeight = UIScreen.main.bounds.height
                    let padding: CGFloat = 26 // 可以根据需要调整额外的间距
                    
                    if screenHeight - keyboardTop < (screenHeight - activeTextFieldY + padding) {
                        keyboardHeight = (screenHeight - activeTextFieldY) - (screenHeight - keyboardTop) + padding
                    }
                }
            }
            NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillHideNotification, object: nil, queue: .main) { _ in
                keyboardHeight = 0
            }
        }
    
    var functionArea: some View {
        HStack {
            Button(action:{
                // 切换账本，类别也要跟着换
                // 显示切换账本弹窗
                showBookChangeSheet = true
            }) {
                BookNameView(book: viewModel.selectedBook)
                    .padding(EdgeInsets(top: 4, leading: 10, bottom: 4, trailing: 10)).background(Color.white.cornerRadius(40))
            }

            Spacer()
            Button(action: { showCalendarSheet = true }) {
                HStack {
                    Image("koi_ic_cal")
                    Text(dateText)
                        .font(.system(size: 14))
                        .foregroundColor(Color.koiColorTitle)
                }.padding(EdgeInsets(top: 4, leading: 10, bottom: 4, trailing: 10)).background(Color.white.cornerRadius(40))
            }
            HStack {
                Text("连续记")
                    .font(.system(size: 14))
                    .foregroundColor(Color.koiColorTitle)
                Toggle("连续记", isOn: $isContinuousRecord).controlSize(.regular).toggleStyle(KoiToggleStyle(onColor: Color.koiColorPrimary, offColor: Color.koiColorDivider, thumbColor: Color.white)).labelsHidden()
            }.padding(EdgeInsets(top: 4, leading: 10, bottom: 4, trailing: 10)).background(Color.white.cornerRadius(40))
        }
        .padding(10)
        .background(LinearGradient(gradient: Gradient(colors: [Color.white.opacity(0),Color.koiColorBackgroundItem]), startPoint: .top, endPoint: .bottom))
    }
    
    private func selectedSubCategory(subCategory:AccountingCategory) {
        viewModel.selectedSubCategory = subCategory
    }
}

extension View {
    func hideKeyboard() {
        UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
    }
}

#Preview {
    AddAccountingView()
}
